/*
 * @Date: 2023-03-21 16:30:48
 * @LastEditTime: 2023-03-27 16:18:20
 *
 * 小程序充当蓝牙外围设备，提供蓝牙服务给其他应用连接
 */

import Tools from '../../utils/tools.js';

const app = getApp();
const tools = new Tools();
let BLEPeripheralServer = null;
let toSendData = new Uint8Array(10);

Page({
  data: {
    serverIdArr: [],
  },

  onLoad() {
    wx.openBluetoothAdapter({
      mode: 'peripheral', //兼容iOS
      success: (res) => {
        //建立本地作为外围设备的服务端
        this.createBLEPeripheralServer();
      },
      fail: (err) => {
        console.log(err);
        //蓝牙未开启
        wx.showToast({ title: '请打开蓝牙', duration: 5000 });
      },
    });
  },

  go() {
    wx.navigateTo({
      url: '/pages/bluetooth/bluetooth',
    });
  },

  //建立本地作为外围设备的服务端 -- 可创建多个
  createBLEPeripheralServer() {
    console.log('创建外围设备');
    wx.createBLEPeripheralServer({
      success: (res) => {
        let data = this.data.serverIdArr;
        const serverId = res.server.serverId;
        if (serverId) {
          if (this.data.serverIdArr.indexOf(serverId) == -1) {
            data.push(serverId);
            this.setData({ serverIdArr: [data] });
          }
        }
        BLEPeripheralServer = res.server;
        console.log(BLEPeripheralServer);
        //添加服务
        this.addService();
      },
      fail(err) {
        wx.showToast({ title: '请打开蓝牙', duration: 5000 });
      },
    });
  },

  // 监听当前外围设备被连接或断开连接事件
  onBLEPeripheralConnectionStateChanged() {
    console.log('监听外围设备动态');
    wx.onBLEPeripheralConnectionStateChanged((res) => {
      console.log(res);
    });
  },

  // 添加服务
  addService() {
    BLEPeripheralServer.addService({
      service: {
        uuid: '0000ff11-0000-1000-8000-00805f9b34fb',
        // characteristics列表
        characteristics: [
          {
            uuid: '0000ff00-0000-1000-8000-00805f9b34fb',
            // 特征支持的操作
            properties: {
              write: true,
              read: true,
              notify: true, //订阅
              indicate: true, //回包
            },
            //特征值权限
            permission: {
              readable: true, //可读
              writeable: true, //可写
              readEncryptionRequired: true, //加密读请求
              writeEncryptionRequired: true, //加密写请求
            },
            // value:ad_data_38,//特征值对应的二进制值
            // value: toSendData, //特征值对应的二进制值
            //描述符数据
            descriptors: [
              {
                uuid: '0000ff01-0000-1000-8000-00805f9b34fb',
                permission: { write: true, read: true },
                // value: toSendData, //描述符数据
              },
            ],
          },
        ],
      },
      success: (res) => {
        console.log(res);
        //开始广播
        this.startAdvertise();
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },

  // 移除服务
  removeService() {
    BLEPeripheralServer.removeService({
      serviceId: '0000ff11-0000-1000-8000-00805f9b34fb',
      success: (res) => {
        console.log(res);
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },

  // 开始广播本地创建的外围设备
  startAdvertise() {
    BLEPeripheralServer.startAdvertising({
      advertiseRequest: {
        deviceName: 'g-service',
        // serviceUuids: ['0000ff11-0000-1000-8000-00805f9b34fb'],
      }, //广播自定义参数
      powerLevel: 'high', //广播功率 -- 合法值 low ，medium，high
      success: (res) => {
        //执行状态监听
        this.onBLEPeripheralConnectionStateChanged();
        //执行写监听
        this.onCharacteristicWriteRequest();
        //执行读监听
        this.onCharacteristicReadRequest();
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },

  // 停止广播本地创建的外围设备
  stopAdvertising() {
    BLEPeripheralServer.stopAdvertising({
      success: (res) => {
        console.log(res);
        this.removeService();
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },

  // 监听已连接的设备请求读当前外围设备的特征值事件  --读
  onCharacteristicReadRequest() {
    console.log('监听已连接的设备请求读当前外围设备的特征值事件');
    //收到该消息后需要立刻调用 writeCharacteristicValue 写回数据，否则主机不会收到响应
    BLEPeripheralServer.onCharacteristicReadRequest((res) => {
      console.log(res);
      //serviceId characteristicId  callbackId
      //callbackId 唯一标识码，调用 writeCharacteristicValue 时使用
    });
  },

  // 监听已连接的设备请求写当前外围设备的特征值事件  -- 写
  onCharacteristicWriteRequest() {
    console.log('监听已连接的设备请求写当前外围设备的特征值事件');
    ////收到该消息后需要立刻调用 writeCharacteristicValue 写回数据，否则主机不会收到响应
    BLEPeripheralServer.onCharacteristicWriteRequest((res) => {
      console.log(res);
      console.log(tools.ab2str(res.value));
      //serviceId characteristicId  callbackId
      //callbackId 唯一标识码，调用 writeCharacteristicValue 时使用
      //value 请求写入的特征值数据
    });
  },

  onHide() {
    this.stopAdvertising();
  },
});
